package com.scalar.chiptrack.adaptor.osep;

import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DataSource;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.SqlQueryMappings;
import com.scalar.ScalarException;

import java.util.ArrayList;
import java.util.Iterator;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
 * User: ChandraSekhar
 * Date: Mar 2, 2007
 * Time: 5:57:44 PM
 */
public class OsepDAO implements AdaptorConstants
{
    private static Logger s_logger = null;
    /**
    * @param dbTransaction
    * @param wipList
    * @throws com.scalar.ScalarException
    */
   public static void saveCMLFGLotDetails( DBTransaction dbTransaction, ArrayList wipList ) throws ScalarException
   {
      Connection conn         = null;
      PreparedStatement pstmt = null;
      boolean success         = false;

      OSEPFGWipStatus wipStatus = null;

      try
      {
          // Get the connection from regular datasource if its not in a manual transaction
          if( dbTransaction == null )
          {
              conn = DataSource.getConnection();
          }
          else
          {
              conn = dbTransaction.getConnection();
          }

			//As wre are calling this before, while saving the OSEP wip lots
          /*pstmt = conn.prepareStatement(SqlQueryMappings.get("adaptor.closeAllFGRunningLots"));
          pstmt.setString(1, VENDOR_NAME_OSEP );
          pstmt.executeUpdate();

          if (pstmt != null)
          {
              pstmt.close();
              pstmt = null;
          }*/


          pstmt = conn.prepareStatement( "{ call sp_save_osep_cml_fg_wip_lots ( ?, ?, ?, ?, ?, ? ) }" );

          Iterator wipStatusIterator = wipList.iterator();

          while( wipStatusIterator.hasNext() )
          {
              wipStatus = ( OSEPFGWipStatus ) wipStatusIterator.next();

              if (wipStatus.getDevice() != null)
              {
                  log( wipStatus + "\n" );

                  pstmt.setString( 1,  wipStatus.getAssyLoc() );
                  pstmt.setString( 2,  wipStatus.getDevice() );
                  pstmt.setString( 3,  wipStatus.getLot() );
                  pstmt.setString( 4,  wipStatus.getSplit() );
                  pstmt.setString( 5,  wipStatus.getActualQtyPulled() );
                  pstmt.setString( 6,  wipStatus.getRec_date() );

                  pstmt.addBatch();
              }
          }

          pstmt.executeBatch();
          success = true;
      }

      catch( SQLException sqle )
      {
          sqle.printStackTrace();
          throw new ScalarException( "Could not save CML FG Wip Information into database", sqle );
      }

      finally
      {

          // Commit/Rollback here it selef -- if its not in a manual transaction
          if( dbTransaction == null )
          {
              try
              {
                  if( conn != null )
                  {
                      if( success == true )
                      {
                          conn.commit();
                      }
                      else
                      {
                          conn.rollback();
                      }
                  }
              }
              catch( SQLException ignore )
              {
              }
          }

          if( pstmt != null )
          {
              try
              {
                  pstmt.close();
              }
              catch( SQLException ignore )
              {
              }
          }
          if( conn != null )
          {
              try
              {
                  conn.close();
              }
              catch( SQLException ignore )
              {
              }
          }
      }
    }

   public static void saveOSEPDieBankLot( DBTransaction dbTransaction, Iterator dieBankLotIterator ) throws ScalarException
   {
      Connection conn         = null;
      PreparedStatement pstmt = null;
      boolean success         = false;

      InventoryLot dieBankStatus = null;

      try
      {
          // Get the connection from regular datasource if its not in a manual transaction
          if( dbTransaction == null )
          {
              conn = DataSource.getConnection();
          }
          else
          {
              conn = dbTransaction.getConnection();
          }

          pstmt = conn.prepareStatement(SqlQueryMappings.get("adaptor.closeAllDieBankLots"));
          pstmt.setString(1, VENDOR_NAME_OSEP);
          pstmt.executeUpdate();
          pstmt = null;

          pstmt = conn.prepareStatement( "{ call SP_CREATE_UPDATE_OSEP_DIEBANK_LOT ( ?, ?, ?, ?, ?, ?, ?, ?, ? ) }" );

          while( dieBankLotIterator.hasNext() )
          {
              dieBankStatus = ( InventoryLot ) dieBankLotIterator.next();

              if (dieBankStatus.getPartNumber() != null)
              {
                  log( dieBankStatus + "\n" );

                  pstmt.setString( 1,  dieBankStatus.getPartNumber() );
                  pstmt.setString( 2,  dieBankStatus.getLotNumber() );
                  pstmt.setString( 3,  dieBankStatus.getFabLotNumber() );
                  pstmt.setString( 4,  dieBankStatus.getQtyIn() );
                  pstmt.setString( 5,  dieBankStatus.getDateIn() );
                  pstmt.setString( 6,  dieBankStatus.getVendorName() );
                  pstmt.setString( 7,  dieBankStatus.getStatus() );
                  pstmt.setString( 8,  INVENTORY_TYPE_DIE_BANK );
                  pstmt.setString( 9,  dieBankStatus.getCategory() );

                  pstmt.addBatch();
              }
          }

          pstmt.executeBatch();
          success = true;
      }

      catch( SQLException sqle )
      {
          sqle.printStackTrace();
          throw new ScalarException( "Could not save OSEP DIE BANK Lot Information into database", sqle );
      }

      finally
      {

          // Commit/Rollback here it selef -- if its not in a manual transaction
          if( dbTransaction == null )
          {
              try
              {
                  if( conn != null )
                  {
                      if( success == true )
                      {
                          conn.commit();
                      }
                      else
                      {
                          conn.rollback();
                      }
                  }
              }
              catch( SQLException ignore )
              {
              }
          }

          if( pstmt != null )
          {
              try
              {
                  pstmt.close();
              }
              catch( SQLException ignore )
              {
              }
          }
          if( conn != null )
          {
              try
              {
                  conn.close();
              }
              catch( SQLException ignore )
              {
              }
          }
       }
    }

    private static void log (String message)
    {
        if ( message == null) return;

        if (s_logger != null)
        {
            synchronized (s_logger)
            {
                s_logger.logDebug (message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println (message);
        }
    }

    public static void setLogger (Logger logger)
    {
        s_logger = logger;
    }
}
